import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_elec_price_setting_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/enums.dart';

class SiteInternetElecDetailController extends GetxController
    with GetTickerProviderStateMixin {
  bool isEnableEdit = false;
  late int id;
  late int  siteId;
  SiteElecPriceSettingModel model = SiteElecPriceSettingModel();
  /// 站点列表服务
  SiteServices siteServices = Get.put(SiteServices());
  RefreshController refreshController = RefreshController(
    initialRefresh: false,
  );
  List<String> titleStringList = [ResKey.basicInfo.tr,ResKey.siteSettingEffectiveDate.tr,ResKey.siteSettingElectricityStagePrice.tr,];
  final TextEditingController ruleNameController = TextEditingController();
  final DeviceServices services = Get.put(DeviceServices());
  List<dynamic> timeDateList = [ {
    'effectiveTime':'01-01',
    'expirationTime':'12-31',
  }];
  List<dynamic> stagePriceList = [
    {
      "intervalStartTime": "00:00",
      "intervalEndTime": "24:00",
      "electricityFees": "1"
    },
  ];

  int status = 1;
  bool isEnableCommit = false;

  @override
  void onInit() {
    if (Get.arguments != null) {
      id = Get.arguments['id'];
      siteId = Get.arguments['siteId'];
    }
    super.onInit();
    if (refreshController.isRefresh) {
      refreshController.refreshCompleted();
    }
    loadData(refereshType: RefereshType.load);
  }
  void edit(){
    isEnableEdit = true;
    update();
  }
  /// 请求站点-光伏上网详情数据
  Future<void> loadData(
      {RefereshType refereshType = RefereshType.refresh}) async {
    Configs.httpClient.requestWithLoading(
          () async {
        var params = {'id': id};
        var data = await siteServices.getSiteInternetDetail(params);
        var temp = SiteElecPriceSettingModel.fromJson(data);
        model = temp;
        ruleNameController.text = model.name!;
        status = model.status!;
        checkCommitStatus();
        if(model.effectiveTimeList != null){
          timeDateList.clear();
          for (var element in model.effectiveTimeList!) {
            timeDateList.add(
                {
                  "effectiveTime": element.effectiveTime,
                  "expirationTime": element.expirationTime,
                }
            );
          }
        }
        if(model.hoursPriceList != null){
          stagePriceList.clear();
          for (var element in model.hoursPriceList!) {
            stagePriceList.add(
                { "intervalStartTime": element.intervalStartTime,
                  "intervalEndTime": element.intervalEndTime,
                  "electricityFees": element.electricityFees
                }
            );
          }
        }
        update();
      },
      onError: (error) {
        refreshController.loadFailed();
        showError(error.message);
        return true;
      },
    );
  }

  ///下一步按钮是否可以点击
  checkCommitStatus() {
    if(ruleNameController.text.isNotEmpty&& timeDateList.isNotEmpty && stagePriceList.isNotEmpty){
      isEnableCommit = true;
    }else{
      isEnableCommit = false;
    }
    update();
  }

  Future<void> save() async {
    var param = {
      "name": ruleNameController.text,
      "status": status,
      "siteId": siteId,
      'type':'0',
      'id':id
    };
    if(timeDateList.isNotEmpty){
      param['effectiveTimeList'] = timeDateList;
    }

    if(stagePriceList.isNotEmpty){
      param['hoursPriceList'] = stagePriceList;
    }

    showLoading(toast:ResKey.loading.tr);
    var result = await services.sitePhotovoltaicAUpdate(param,onError: (p0) {

      dismissLoading();
      handleException(p0);
      return false;
    },);
    dismissLoading();
    if(result==true){
      Get.back(result: true);
    }
  }

  void cancelEdit(){
    isEnableEdit = false;
    update();
  }

  void updateTimeList(){
    timeDateList.addAll([ {
      "effectiveTime": "01-01",
      "expirationTime": "12-31"
    }]);
    checkCommitStatus();
    update();
  }

  void deleteTimeList(int index){
    timeDateList.removeAt(index);
    checkCommitStatus();
    update();
  }

  void updateStagePriceList(){
    stagePriceList.addAll([ {
      "intervalStartTime": "00:00",
      "intervalEndTime": "24:00",
      "electricityFees": "1"
    }]);
    checkCommitStatus();
    update();
  }

  void deleteStagePriceList(int index){
    stagePriceList.removeAt(index);
    checkCommitStatus();
    update();
  }
}